<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="mesSalesOrderTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      class="dialog-pack"
      size="60%"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
    >
      <template v-slot:customerName>
        <!-- 插槽内容有el-form-item组件包裹 -->
        <el-input
          v-model="formDataDialog.customerName"
          readonly
          :placeholder="$t('mesSalesOrder.selectCustomer')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="click"
          ></el-button>
        </el-input>
      </template>
    </ele-form-drawer>
    <ele-dialog-table
      :title="$t('mesSalesOrder.customerQuery')"
      width="800px"
      :visible.sync="mesCustomerDialogVisible"
      :formConfig="mesCustomerSearchDialog"
      :column="mesCustomerDialogColumn"
      @getSelectData="getSelectCustomer"
      :getList="getSelectCustomerList"
      :hasFooter="hasMesSalesOrderFooter"
    >
    </ele-dialog-table>
    <dialogTable :type="2" ref="dialogTable" @responseList="responseList" />
  </div>
</template>

<script>
import { operateList, searchConfig, rowConfig } from "./config";
import { formDescDialog } from "./table";
import dialogTable from "./components/ele-dialog-table/index.vue";
import { popover } from "@/utils/judge";
import {
  getList,
  rowCreate,
  rowUpdate,
  rowDel,
  rowDetail,
  getDeliveryMethodList,
} from "@/api/order/mesSalesOrder";
import { mesCustomerDialog } from "./mixin";
import { getBaseCodeStrategy } from "@/api/common";
import url from "@/axios/url";
const { minioUrl } = url();
export default {
  name: "mesSalesOrder",
  mixins: [formDescDialog, operateList, mesCustomerDialog],
  components: { dialogTable },
  data() {
    return {
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: { codeStrategy: "" },
      searchConfig,
      getList,
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
          fixed: "left",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          width: 60,
          fixed: "left",
        },
        {
          prop: "salesOrderCode",
          label: $i18n.t("mesSalesOrder.salesOrderCode"),
          minWidth: "200",
          showOverflowTooltip: true,
          render: (h, scope) => {
            return popover(scope.row.salesOrderCode, h, "", () =>
              this.handleJump(scope.row)
            );

            // return (
            //   <el-link
            //     onClick={() => this.handleJump(scope.row)}
            //     type="primary"
            //   >
            //     {scope.row.salesOrderCode}
            //   </el-link>
            // );
          },
        },
        {
          prop: "customerCode",
          label: $i18n.t("mesSalesOrder.customerCode"),
          minWidth: "150",
          showOverflowTooltip: true,
        },
        {
          prop: "customerName",
          label: $i18n.t("mesSalesOrder.customerName"),
          minWidth: "240",
          align: "center",
          showOverflowTooltip: true,
        },
        {
          prop: "telephone",
          label: $i18n.t("mesSalesOrder.telephone"),
          minWidth: "140",
          showOverflowTooltip: true,
        },
        {
          prop: "deliveryMethod",
          label: $i18n.t("mesSalesOrder.deliveryMethod"),
          minWidth: "130",
          showOverflowTooltip: true,
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getDeliveryMethodList();
            return list.data.result;
          },
        },
        {
          prop: "deliveryAddress",
          label: $i18n.t("mesSalesOrder.deliveryAddress"),
          width: 160,
          // align: "left",
          // showOverflowTooltip: true,
          render: (h, scope) => {
            return popover(scope.row.deliveryAddress, h);
          },
        },
        {
          prop: "customerOrderCode",
          label: $i18n.t("mesSalesOrder.customerOrderCode"),
          width: "160",
        },
        {
          prop: "planDeliveryDate",
          label: $i18n.t("mesSalesOrder.planDeliveryDate"),
          minWidth: "140",
          showOverflowTooltip: true,
        },
        // {
        //   prop: "remark",
        //   label: "备注",
        //   width: "120",
        //   showOverflowTooltip: true,
        // },
        {
          prop: "createByName",
          label: $i18n.t("common.createByName"),
          width: "130",
          showOverflowTooltip: true,
        },
        {
          prop: "createTime",
          label: $i18n.t("common.createTime"),
          width: "170",
          // showOverflowTooltip: true,
        },
        {
          prop: "updateByName",
          label: $i18n.t("common.updateByName"),
          width: "130",
          showOverflowTooltip: true,
        },
        {
          prop: "updateTime",
          label: $i18n.t("common.updateTime"),
          width: "170",
          // showOverflowTooltip: true,
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"),
          width: 160,
          fixed: "right",
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              />
            );
          },
        },
      ],
    };
  },
  computed: {},
  created() {
    this.getBaseCodeStrategy();
  },
  methods: {
    handleJump(row) {
      console.log(row, "点击行");
      this.$router.push({
        path: "/order/mesSalesOrder/detail",
        query: {
          id: row.salesOrderCode,
        },
      });
    },
    click() {
      this.mesCustomerDialogVisible = true;
    },
    // 表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name;
      const { codeStrategy } = this.formDataDialog;
      const fnc = {
        add: () => {
          this.disableFields(false);
          console.log("codeStrategy", codeStrategy);
          this.formDataDialog = { codeStrategy };
          this.visible = true;
        },
        deleteBatch: () => {
          this.$confirm(
            $i18n.t("common.deleteBatch", {
              name: $i18n.t("mesSalesOrder.name"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            const ids = data.rows.map((val) => val.id).join(",");
            this.rowDel(ids);
          });
        },
        exportExcel: () => {
          var urlexportExcel = `${minioUrl}/mes-template/销售订单模板.zip`;
          window.open(urlexportExcel);
        },
      };
      fnc[data.handleName]();
    },
    // 表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        edit: () => {
          this.disableFields(false);
          this.rowDetail(row.id);
          this.visible = true;
        },
        detail: () => {
          this.disableFields(true);
          this.rowDetail(row.id);
          this.visible = true;
        },
        delete: () => {
          this.$confirm(
            $i18n.t("common.deleteSingle", {
              name: $i18n.t("mesSalesOrder.name"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            this.rowDel(row.id);
          });
        },
      };
      fnc[handleName]();
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true;
      const code = data.salesOrderCode;
      let checkList = data.mesSalesOrderDetailList || [];
      if (checkList.length === 0) {
        this.$message.warning($i18n.t("mesSalesOrder.submitErrMsg1"));
        this.isLoading = false;
        return;
      }
      checkList.forEach((item) => {
        if (!item.lineNum || !item.count) {
          this.$message.warning($i18n.t("mesSalesOrder.submitErrMsg2"));
          this.isLoading = false;
          return;
        }
      });
      const list = data.mesSalesOrderDetailList.map((item) => item.lineNum);
      if (new Set(list).size !== list.length) {
        this.$message.warning($i18n.t("mesSalesOrder.submitErrMsg3"));
        this.isLoading = false;
        return;
      }

      data.mesSalesOrderDetailList = data.mesSalesOrderDetailList.map(
        (item) => {
          return {
            ...item,
            salesOrderCode: code,
          };
        }
      );
      api(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || title);
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    // 弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return; // 判断状态
      const params = this.formDataDialog.id
        ? { title: $i18n.t("common.editSuccess"), api: rowUpdate, data }
        : { title: $i18n.t("common.addSuccess"), api: rowCreate, data };
      this.doSubmit(params);
    },
    // 删除
    rowDel(data) {
      this.loading = true;
      rowDel(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.deleteSuccess"));
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag;
      this.formDescDialog.isShowSubmitBtn = !flag;
    },
    rowDetail(id) {
      rowDetail(id).then((res) => {
        this.formDataDialog = res.data.result;
      });
    },
    // 刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },
    //判断是否存在编码规则
    getBaseCodeStrategy() {
      getBaseCodeStrategy({
        code: "salesordercode",
        system: "default",
        strategyStatus: "1",
      }).then((res) => {
        // console.log("判断是否存在编码规则", res);
        const result = res.data.result;
        this.formDataDialog.codeStrategy =
          Array.isArray(result) && result.length > 0 ? result[0].code : "";
        if (!!this.formDataDialog.codeStrategy) {
          this.setFormDescDialogRequired(false);
        } else {
          this.setFormDescDialogRequired(true);
        }
      });
    },
    setFormDescDialogRequired(bool = false) {
      this.$set(this.formDescDialog.formDesc.salesOrderCode, "required", bool);
    },
  },
};
</script>
